package com.atguigu.bigdata.chapter05.sink;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer;
import org.apache.flink.util.Collector;

import java.util.Properties;

/**
 * @Author lzc
 * @Date 2022/9/2 9:04
 */
public class Flink01_Sink_Kafka {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        // 如果没有设置并行度, 并行度的值是cpu的核心数据
        Properties props = new Properties();
        props.setProperty("bootstrap.servers", "hadoop162:9092");
        env
            .readTextFile("input/words.txt")
            .flatMap(new FlatMapFunction<String, Tuple2<String, Long>>() {
                @Override
                public void flatMap(String value, Collector<Tuple2<String, Long>> out) throws Exception {
                    for (String word : value.split(" ")) {
                        out.collect(Tuple2.of(word, 1L));
                    }
                }
            })
            .keyBy(t -> t.f0)
            .sum(1)
            .map(t -> t.f0 + "_" + t.f1)
            // 参数1: 写出的topi
            // 参数2: 序列化器
            // 参数2: kafka的配置信息
            .addSink(new FlinkKafkaProducer<String>("s1", new SimpleStringSchema(), props));
        
        
        env.execute();
    }
}
